package com.example.webcourse.jsUse

import android.annotation.SuppressLint
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import com.example.webcourse.R

class JsUseActivity : AppCompatActivity() {
    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_js_use)
        val webView = findViewById<WebView>(R.id.webView)
        webView.settings.javaScriptEnabled = true
        webView.settings.javaScriptCanOpenWindowsAutomatically = true
        // 不推荐，会有js注入问题 反射获取手机系统信息
//        webView.addJavascriptInterface(AndroidToJs(), "test")
        webView.loadUrl("file:///android_asset/js.html")
        // 点击按钮后重定向，拦截url
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                //       scheme://authority
                //url = "js://webview?arg1=111&arg2=222"
                val uri = Uri.parse(url)
                if (uri.scheme.equals("js")) {
                    if (uri.authority.equals("webview")) {
                        println("js调用Android方法")
//                        val params = HashMap<String, String>()
                        val names = uri.queryParameterNames
                    }
                    return true
                }
                return super.shouldOverrideUrlLoading(view, url)
            }
        }
    }
}